package cz.najman.emdroid.content;

import java.text.ParseException;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import android.content.ContentValues;
import cz.najman.emdroid.mappings.Mappings;

/**
 * @author  Lukáš Najman
 */
public class SmartContentHandler extends ContentHandler {

	private static final String TAG = "SmartContentHandler";
	
	Mappings mappingObject;
	Map<String, String> mMappings;
	
	public SmartContentHandler(Mappings mappingObject) {
		this.mappingObject = mappingObject;
		this.mMappings = mappingObject.getToDbMappings();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {

		if(mMappings.containsKey(localName)){
			String key = mMappings.get(localName);
			
			if(key == Mappings.START_TAG){
				mValues = new ContentValues();
			} else {
				mBulider.delete(0, mBulider.length());
			}
			
			int attLenght = atts.getLength();
			if(attLenght != 0){
				for(int i = 0; i < attLenght; i++){
					String name = atts.getLocalName(i);
					if(mMappings.containsKey(name)){
						mValues.put(mMappings.get(name), atts.getValue(i));
					}
				}
			}
		} 
		
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		
		if(mMappings.containsKey(localName)){
			String key = mMappings.get(localName);
			
			if(key == Mappings.START_TAG){				
				mListener.send(mValues, mRequestId);
			} else {
				String value = "";
				if(mappingObject.getDates().contains(key)){
					try {
						value = String.valueOf(mSdf.parse(mBulider.toString()).getTime());						
					} catch (ParseException e) {						
						e.printStackTrace();
					}
				} else {
					value = mBulider.toString();
				}
				
				mValues.put(key, value);		
				
			}
		}			
			
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		mBulider.append(ch, start, length);
	}
	
	
	public void setMappings(Mappings mappingObject) {
		this.mappingObject = mappingObject;
		this.mMappings = mappingObject.getToDbMappings();
	}
	
}
